package cn.juque.common.fastjson.serializer;

import cn.juque.common.fastjson.abstracts.AbstractTypeReference;
import cn.juque.common.utils.FastJsonUtil;
import com.alibaba.fastjson2.JSONReader.Feature;
import com.alibaba.fastjson2.JSONWriter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author nuoka
 * @version 1.0.0
 * <li>IntelliJ IDEA</li>
 * <li>cn.juque.cn.juque.common.serializer</li>
 * @date 2020/4/4 15:56
 **/
@Slf4j
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {

  private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

  public FastJson2JsonRedisSerializer() {
    super();
  }

  @Override
  public byte[] serialize(T o) throws SerializationException {
    if (o == null) {
      return new byte[0];
    }
    String json = FastJsonUtil.toJsonString(o, JSONWriter.Feature.WriteClassName);
    return json.getBytes(DEFAULT_CHARSET);
  }

  @Override
  public T deserialize(byte[] bytes) throws SerializationException {
    if (bytes == null || bytes.length == 0) {
      return null;
    }
    String str = new String(bytes, DEFAULT_CHARSET);
    return FastJsonUtil.parseObject(str, new AbstractTypeReference<T>() {}, Feature.SupportAutoType);
  }
}
